/*
 * MIT License
 *
 * Copyright (c) 2023 北京凯特伟业科技有限公司
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */
package com.je.meta.util;

import com.alibaba.druid.pool.DruidDataSource;
import com.google.common.base.Strings;
import com.xxl.job.core.executor.impl.XxlJobSpringExecutor;
import org.springframework.core.env.Environment;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import redis.clients.jedis.JedisPoolConfig;

public class ConfigUtil {

    public static DruidDataSource getDruidDataSource(Environment environment){
        DruidDataSource ds = new DruidDataSource();
        ds.setDriverClassName(environment.getProperty("jdbc.driverClassName"));
        //设置链接地址
        ds.setUrl(environment.getProperty("jdbc.url"));
        //设置用户名
        ds.setUsername(environment.getProperty("jdbc.username"));
        //设置密码
        ds.setPassword(environment.getProperty("jdbc.password"));
        //设置验证查询
        ds.setValidationQuery(environment.getProperty("jdbc.validationQuery"));
        //单位：秒，检测连接是否有效的超时时间。底层调用jdbc Statement对象的void setQueryTimeout
        ds.setValidationQueryTimeout(600);
        //初始化大小
        ds.setInitialSize(environment.getProperty("jdbc.initialSize",Integer.class));
        ds.setMinIdle(environment.getProperty("jdbc.minIdle",Integer.class));
        ds.setMaxActive(environment.getProperty("jdbc.maxActive",Integer.class));
        //配置获取连接等待超时的时间
        ds.setMaxWait(60000);
        //配置间隔多久才进行一次检测，检测需要关闭的空闲连接，单位是毫秒
        ds.setTimeBetweenEvictionRunsMillis(60000);
        //配置一个连接在池中最小生存的时间，单位是毫秒
        ds.setMinEvictableIdleTimeMillis(200000);
        ds.setTestWhileIdle(true);
        //这里建议配置为TRUE，防止取到的连接不可用
        ds.setTestOnBorrow(false);
        ds.setTestOnReturn(false);
        //打开PSCache，并且指定每个连接上PSCache的大小
        ds.setPoolPreparedStatements(true);
        //配置每个链接最大打开的Statement数量
        ds.setMaxPoolPreparedStatementPerConnectionSize(20);
        //这里配置提交方式，默认就是TRUE，可以不用配置
        ds.setDefaultAutoCommit(true);
        //超过时间限制是否回收
        ds.setRemoveAbandoned(false);
        //回收超时时间；单位为秒。180秒=3分钟
        ds.setRemoveAbandonedTimeout(60);
        //关闭abanded连接时输出错误日志
        ds.setLogAbandoned(true);
        return ds;
    }

    public static JedisConnectionFactory createRedisConnectionFactory(Environment environment){
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxIdle(environment.getProperty("redis.maxIdle",Integer.class));
        poolConfig.setMaxTotal(environment.getProperty("redis.maxTotal",Integer.class));
        poolConfig.setTestOnBorrow(environment.getProperty("redis.testOnBorrow",Boolean.class));
        poolConfig.setMaxWaitMillis(1000*2);

        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(poolConfig);
        jedisConnectionFactory.getStandaloneConfiguration().setHostName(environment.getProperty("redis.host"));
        jedisConnectionFactory.getStandaloneConfiguration().setPort(environment.getProperty("redis.port",Integer.class));
        jedisConnectionFactory.getStandaloneConfiguration().setPassword(environment.getProperty("redis.pass"));
        jedisConnectionFactory.getStandaloneConfiguration().setDatabase(environment.getProperty("redis.dbindex",Integer.class));
        return jedisConnectionFactory;
    }

    public static XxlJobSpringExecutor createXxlExecutor(Environment environment){
        XxlJobSpringExecutor xxlJobSpringExecutor = new XxlJobSpringExecutor();
        xxlJobSpringExecutor.setAdminAddresses(environment.getProperty("xxl.job.admin.addresses"));
        xxlJobSpringExecutor.setAppname(environment.getProperty("xxl.job.executor.appname"));
        xxlJobSpringExecutor.setAddress(environment.getProperty("xxl.job.executor.address"));
        if (!Strings.isNullOrEmpty(environment.getProperty("xxl.job.executor.ip"))) {
            xxlJobSpringExecutor.setIp(environment.getProperty("xxl.job.executor.ip"));
        }
        if (!Strings.isNullOrEmpty(environment.getProperty("xxl.job.executor.port"))) {
            xxlJobSpringExecutor.setPort(Integer.parseInt(environment.getProperty("xxl.job.executor.port")));
        }
        xxlJobSpringExecutor.setAccessToken(environment.getProperty("xxl.job.accessToken"));
        if (!Strings.isNullOrEmpty(environment.getProperty("xxl.job.executor.logpath"))) {
            xxlJobSpringExecutor.setLogPath(environment.getProperty("xxl.job.executor.logpath"));
        }
        if (!Strings.isNullOrEmpty(environment.getProperty("xxl.job.executor.logretentiondays"))) {
            xxlJobSpringExecutor.setLogRetentionDays(Integer.parseInt(environment.getProperty("xxl.job.executor.logretentiondays")));
        }
        return xxlJobSpringExecutor;
    }
}
